from myelin.Ns import MYELINS
from myelin.server.core.ft import ModelDriver

from nodetypes.Ns import GRAPHS_NS

class AgentProfiler(object):
    __slots__ = ('root','locale',)
    
    newAgentDriver = staticmethod(ModelDriver.FromRepo)
    newProfilesDriver = staticmethod(ModelDriver.FromRepo)
    
    def __init__(self, root, locale=None):
        self.root = root
        self.locale = locale
    
    def createProfile(self, context, node, model, name, ns):
        #print "Node %s: %s, %s" % (model.rdf_value, root, locale)
        graphs = context.server.graphs
        value = graphs[GRAPHS_NS + 'agents']['public']
        if value:
            agentModel = model.rdf_clone(
                model.Initialize(
                    self.newAgentDriver(
                        context.repo,
                        value
                    )
                )
            )
        else:
            agentModel = model
            
        map = context.uriMapper.apply
        attrs = {
            u'node-id' : model.rdf_value
        }
        
        m_join = agentModel.rdf_join
        value = m_join('foafNick')
        if value:
            attrs[u'nick'] = value
        value = m_join('foafName')
        if value:
            attrs[u'name'] = value
            
        node = node.xml_append(
            node.xml_create_element(
                name, ns,
                attributes = attrs
            )
        )
            
        locale = self.locale
        root = self.root
        def _profile(m):
            for p in m:
                #print "profile: %s" % p.rdf_value
                href = map(p.rdf_getDomain())
                if href.startswith('http://'):
                    if locale in p.dcLanguage:
                        return (p.rdf_value, href)
                    r = _profile(p.mTranslation)
                    if r: return r
                    # should we just return what we found?
                    # return p 
        
        value = graphs[GRAPHS_NS + 'profiles']['published']
        if value:
            model = model.rdf_clone(
                model.Initialize(
                    self.newProfilesDriver(
                        context.repo,
                        value
                    )
                )
            )
        
        value = _profile(model.mProfile)
        if value:
            node.xml_append(
                node.xml_create_element(
                    u'a:profile', MYELINS,
                    attributes = {
                        u'node-id'      : value[0],
                        u'uri'         : value[1],
                    }
                )
            )
            
        return node